const { executeQuery, executePagedQuery } = require('../utils/dataAccess');
const getTime = require('../utils/getTime');
const { v4: uuidv4 } = require('uuid');

exports.getUserList = async (req, res, next) => {
    let whereClause = ` where 1=1 `

    if(req.body.nickName){whereClause += ` and u.nick_name like '%${req.body.nickName}%'`;}
    if(req.body.postId){whereClause += ` and up.post_id = '${req.body.postId}'`;}
    if(req.body.roleId){whereClause += ` and ur.role_id = '${req.body.roleId}'`;}
    if(req.body.deptId){whereClause += ` and u.dept_id = '${req.body.deptId}'`;}
    if(req.body.status){whereClause += ` and u.status = '${req.body.status}'`;}

    let sqlStatement = `SELECT   
            u.avatar AS avatar,  
            u.create_time AS createTime,  
            u.create_by AS createBy,  
            u.dept_id AS deptId,  
            u.nick_name AS nickName,  
            u.password AS password,  
            u.phonenumber AS phoneNumber,  
            u.remark AS remark,  
            u.sex AS sex,  
            u.status AS status,  
            u.user_id AS userId,  
            u.user_name AS userName,  
            d.dept_name AS deptName,
            ur.role_id AS roleId,
            r.role_name AS roleName,
            up.post_id AS postId,
            p.post_name AS postName
        FROM   
            sys_user u  
        JOIN   
            sys_dept d ON u.dept_id = d.dept_id 
        LEFT JOIN
            sys_user_role ur ON u.user_id = ur.user_id
        LEFT JOIN
            sys_role r ON ur.role_id = r.role_id
        LEFT JOIN
            sys_user_post up ON u.user_id = up.user_id
        LEFT JOIN
            sys_post p ON up.post_id = p.post_id
        ${whereClause}  
        `;
    const { pageSize, pageNo} = req.body;
    
    try {
        const data = await executePagedQuery(sqlStatement, pageSize, pageNo, 'userId');
        res.json({
            code: 200,
            message: '查询成功',
            data: data
        });
    } catch (error) {
        next(error);
    }
};

exports.switchUserStatus = async (req, res, next) => {

    try {
        if(!req.body.userId){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `UPDATE sys_user SET status = '${req.body.status}' WHERE user_id = ${req.body.userId }`;

        let result = await executeQuery(sqlStatement);
        res.json({
            code: 200,
            message: '操作成功',
            data: result.rows
        })
    }
    catch (err) {
        next(err);
    }
}

exports.addUser = async (req, res, next) => {
    

    try {
        if(!req.body.userName || !req.body.password || !req.body.nickName || !req.body.status || !req.body.deptId){
            throw new Error('参数错误');
        }
    
        let createBy = req.auth.user_name
        let createTime = getTime()
    
    
        let sqlStatement = `INSERT INTO sys_user (user_name, password, nick_name, status, dept_id, create_by, create_time, avatar, phonenumber, remark) VALUES (
            '${req.body.userName}',
            '${req.body.password}',
            '${req.body.nickName}',
            '${req.body.status}',
            '${req.body.deptId}',
            '${createBy}',
            '${createTime}',
            '${req.body.avatar}',
            '${req.body.phoneNumber}',
            '${req.body.remark}'
        )`;

        const result = await executeQuery(sqlStatement); // 执行SQL语句
        res.json({
            code: 200, 
            message: '添加用户成功',
            data: result.rows
        });
    }
    catch (err) {
        next(err)
    }
}

exports.updateUser = async (req, res, next) => {

    try {

        if(!req.body.userId || !req.body.status || !req.body.deptId){
            throw new Error('参数错误');
        }
        let updateBy = req.auth.user_name
        let updateTime = getTime()
    
        let roleSql = ` `;
        let postSql = ` `;
    
        // 首先检查sys_user_role与sys_user_post中是否存在该用户的角色和岗位信息，如果存在则更新，否则插入新记录
        let checkRoleSql = `SELECT * FROM sys_user_role WHERE user_id = ${req.body.userId}`; // 检查用户角色信息是否存在
        let checkPostSql = `SELECT * FROM sys_user_post WHERE user_id = ${req.body.userId}`; // 检查用户岗位信息是否存在
    
        let sqlStatement = `
        UPDATE sys_user  
        SET   
            user_name = '${req.body.userName}',  
            nick_name = '${req.body.nickName}',
            password = '${req.body.password}', 
            status = '${req.body.status}',  
            dept_id = '${req.body.deptId}',  
            avatar = '${req.body.avatar}',  
            phonenumber = '${req.body.phoneNumber}',  
            remark = '${req.body.remark}',
            update_by = '${updateBy}',
            update_time = '${updateTime}'
        WHERE   
            user_id = '${req.body.userId}';
        `


        const checkRoleResult = await executeQuery(checkRoleSql); // 执行SQL语句，检查用户角色信息是否存在
        const checkPostResult = await executeQuery(checkPostSql); // 执行SQL语句，检查用户岗位信息是否存在

        if(checkRoleResult.rows.length > 0 && req.body.roleId){
            roleSql = `UPDATE sys_user_role SET role_id = ${req.body.roleId} WHERE user_id = ${req.body.userId}`; // 更新用户角色信息
        }else{
            roleSql = `INSERT INTO sys_user_role (user_id, role_id) VALUES (${req.body.userId}, ${req.body.roleId})`; // 插入新用户角色信息
        }

        if(checkPostResult.rows.length > 0 && req.body.postId){
            postSql = `UPDATE sys_user_post SET post_id = ${req.body.postId} WHERE user_id = ${req.body.userId}`; // 更新用户岗位信息
        }else{
            postSql = `INSERT INTO sys_user_post (user_id, post_id) VALUES (${req.body.userId}, ${req.body.postId})`; // 插入新用户岗位信息
        }

        const result = await executeQuery(sqlStatement); // 执行SQL语句
        let roleResult = null
        let postResult = null
        if(req.body.roleId){
            roleResult = await executeQuery(roleSql); // 执行SQL语句
        }
        if(req.body.postId){
            postResult = await executeQuery(postSql); // 执行SQL语句
        }

        res.json({
            code: 200, 
            message: '更新用户成功',
            data: {
                result: result.rows,
                roleResult: roleResult,
                postResult: postResult
            },
        })
    }
    catch (err) { // 捕获任何错误并返回错误响应
        next(err); // 返回错误响应
    }
}

// 删除用户信息，包括用户角色和用户岗位信息
exports.deleteUser = async (req, res, next) => {
    try {
        if(!req.body.userId){
            throw new Error('用户ID不能为空');
        }
        let sqlStatement = `DELETE FROM sys_user WHERE user_id = ${req.body.userId}`;
        let roleSql = `DELETE FROM sys_user_role WHERE user_id = ${req.body.userId}`;
        let postSql = `DELETE FROM sys_user_post WHERE user_id = ${req.body.userId}`;

        const result = await executeQuery(sqlStatement); // 执行SQL语句
        let roleResult = await executeQuery(roleSql); // 执行SQL语句
        let postResult = await executeQuery(postSql); // 执行SQL语句

        res.json({
            code: 200, 
            message: '删除用户成功',
            data: {result, roleResult, postResult},
        })
    }
    catch (err) {
        next(err)
    }
}